package co.yixiang.modules.shop.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class LiveUtils {
    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String key="d44c090ce2929b338d1325ce5a98d75d";

    /**
     * 获取开启推流鉴权后生成的鉴权串
     *
     * @param streamName 流名称，用户自定义，用于标识直播流
     * @param txTime     推流地址设置的时间戳，是控制台推流地址的有效时间。
     * @return
     */
    public static String getSafeUrl( String streamName, long txTime) {
        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();
        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return  txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }


    public static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];
        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }

    /**
     * 获取直播推流地址
     * @param txSecret 开启推流鉴权后生成的鉴权串
     */
    public static String getLiveUrl(String StreamName,String txSecret){
          String liveUrl="rtmp://tuiliu.xjystreet.com/live/"+StreamName+"?"+txSecret;
          return liveUrl;
    }
    /**
     * 获取直播观看地址
     * @param txSecret 开启推流鉴权后生成的鉴权串
     */
    public static String getWatchUrl(String txSecret,String streamName){
        String liveUrl="http://bofang.xjystreet.com/live/"+streamName+".flv?"+txSecret;
        return liveUrl;
    }


    public static void main(String[] args) {
        System.out.println(getLiveUrl("11212122",getSafeUrl( "11212122", 1469762325L)));
    }
}
